#include <QDateTime>
#include <QSint>
#include <QTimer>
#include "mainwindow.h"
#include "webviewform.h"
#include "profileform.h"
#include "postform.h"
#include "logform.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    initMainWindow();
    readSettings();
    createActions();
    createConnections();
    createToolBar();
    profile = new Profile(this);
    if (autostart) {
        qDebug() << "AUTOSTART AFTER 3 SECONDS";
        QTimer::singleShot(3000, this, SLOT(addWeb()));
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::writeLog(const int &dest, const QString &text)
{
    QString timeStamp(QTime::currentTime().toString("hh:mm:ss"));
    switch (dest)
    {
        case 0:
            ui->logTextEdit->append(timeStamp + " " + text);
            break;
        case 1:
            trayIcon->showMessage("qBotbaBot", timeStamp + " " + text);
            ui->logTextEdit->append(timeStamp + " " + text);
            break;
        default:
            break;
    }
}

void MainWindow::initMainWindow()
{
    ui->setupUi(this);
    infoLabel = new QLabel(this);
    ui->mainStatusBar->addWidget(infoLabel);
    clockLabel= new QLabel("Time");
    ui->mainStatusBar->addPermanentWidget(clockLabel);
    timer.setInterval(1000);
    timer.start();

    optionsDialog = new OptionsDialog(this);

    trayIcon     = 0;
    trayIconMenu = 0;
    createTrayIcon();
}

void MainWindow::addWeb()
{
    int index;
    if (profile->webView == NULL)
    {
        profile->webView = new WebViewForm(ui->stackedWidget);
        index = ui->stackedWidget->addWidget(profile->webView);
        connect((WebViewForm *)(ui->stackedWidget->widget(index)), SIGNAL(log(int, QString)), this, SLOT(writeLog(int, QString)));
    }
    else
    {
        index = ui->stackedWidget->indexOf(profile->webView);
    }
    ui->stackedWidget->setCurrentIndex(index);
}

void MainWindow::addConfig()
{
    int index;
    if (profile->profile == NULL)
    {
        profile->profile = new ProfileForm(ui->stackedWidget);
        index = ui->stackedWidget->addWidget(profile->profile);
        ui->stackedWidget->setCurrentIndex(index);
    }
    else
    {
        index = ui->stackedWidget->indexOf(profile->profile);
    }
    ui->stackedWidget->setCurrentIndex(index);
}

void MainWindow::addLog()
{
    int index;
    if (profile->log == NULL)
    {
        profile->log = new LogForm(ui->stackedWidget);
        index = ui->stackedWidget->addWidget(profile->log);
        ui->stackedWidget->setCurrentIndex(index);
    }
    else
    {
        index = ui->stackedWidget->indexOf(profile->log);
    }
    ui->stackedWidget->setCurrentIndex(index);
}

void MainWindow::addPost()
{
    int index;
    if (profile->post == NULL)
    {
        profile->post = new PostForm(ui->stackedWidget);
        index = ui->stackedWidget->addWidget(profile->post);
        ui->stackedWidget->setCurrentIndex(index);
    }
    else
    {
        index = ui->stackedWidget->indexOf(profile->post);
    }
    ui->stackedWidget->setCurrentIndex(index);
}

void MainWindow::addStaff()
{
    int index;
    if (profile->staff == NULL)
    {
        profile->staff = new StaffForm(ui->stackedWidget);
        index = ui->stackedWidget->addWidget(profile->staff);
        ui->stackedWidget->setCurrentIndex(index);
    }
    else
    {
        index = ui->stackedWidget->indexOf(profile->staff);
    }
    ui->stackedWidget->setCurrentIndex(index);
}

void MainWindow::createConnections()
{
    connect(&timer, SIGNAL(timeout()), this, SLOT(timeRefresh()));
    connect(ui->quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(ui->aboutAction, SIGNAL(triggered()), this, SLOT(aboutBotvaBot()));
    connect(ui->optionsAction, SIGNAL(triggered()), this, SLOT(options()));
    connect(ui->aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

//    connect(ui->loginPushButton, SIGNAL(clicked()), this, SLOT(login()));
//    connect(ui->indexPushButton, SIGNAL(clicked()), this, SLOT(index()));
//    connect(ui->dozorPushButton, SIGNAL(clicked()), this, SLOT(dozor()));
//    connect(ui->mineOpenPushButton, SIGNAL(clicked()), this, SLOT(mineOpen()));
//    connect(ui->mineShopPushButton, SIGNAL(clicked()), this, SLOT(mineShop()));
//    connect(ui->farmPushButton,  SIGNAL(clicked()), this, SLOT(farm()));
//    connect(ui->shopPushButton,  SIGNAL(clicked()), this, SLOT(shop()));
//    connect(ui->housePushButton, SIGNAL(clicked()), this, SLOT(house()));
//    connect(ui->trainPushButton, SIGNAL(clicked()), this, SLOT(training()));
//    connect(ui->villagePushButton, SIGNAL(clicked()), this, SLOT(village()));
//    connect(ui->witchPushButton, SIGNAL(clicked()), this, SLOT(witch()));
//    connect(ui->postPushButton, SIGNAL(clicked()), this, SLOT(post()));
//    connect(ui->smithPushButton, SIGNAL(clicked()), this, SLOT(smith()));

//    //====== DEBUG ===========
//    connect(ui->smallGladePushButton, SIGNAL(clicked()), this, SLOT(debug1()));
//    connect(ui->pushButton2, SIGNAL(clicked()), this, SLOT(debug2()));
}

void MainWindow::createActions()
{
    // main tool bar actions

    // add profiles bar
    QSint::ActionGroup *tb = ui->profileActionPanel->createGroup(tr("%1@%2").arg(nick).arg(gameServer), true);
    webAction = new QAction("Web", this);
    connect(webAction, SIGNAL(triggered()), this, SLOT(addWeb()));
    tb->addAction(webAction);
    postAction = new QAction("Post", this);
    connect(postAction, SIGNAL(triggered()), this, SLOT(addPost()));
    tb->addAction(postAction);
    staffAction = new QAction("Staff", this);
    connect(staffAction, SIGNAL(triggered()), this, SLOT(addStaff()));
    tb->addAction(staffAction);
    profileAction = new QAction("Config", this);
    connect(profileAction, SIGNAL(triggered()), this, SLOT(addConfig()));
    tb->addAction(profileAction);
    logAction = new QAction("Log", this);
    connect(logAction, SIGNAL(triggered()), this, SLOT(addLog()));
    tb->addAction(logAction);
    ui->profileActionPanel->addStretch();
}

void MainWindow::createToolBar()
{
    ui->mainToolBar->addAction(ui->actionStart);
    ui->mainToolBar->addAction(ui->actionPause);
    ui->mainToolBar->addAction(ui->actionStop);
    connect(ui->actionStart, SIGNAL(triggered()), this, SLOT(startBot()));
    connect(ui->actionPause, SIGNAL(triggered()), this, SLOT(pauseBot()));
    connect(ui->actionStop, SIGNAL(triggered()), this, SLOT(stopBot()));
}

void MainWindow::startBot()
{
    ui->actionStart->setEnabled(false);
    ui->actionPause->setEnabled(true);
    ui->actionStop->setEnabled(true);
    ui->actionPause->setIcon(QIcon(":/icons/Step-Forward-Normal-Blue-icon.png"));
    ui->actionPause->setChecked(false);
//    emit work();
}

void MainWindow::pauseBot()
{
    ui->actionStart->setEnabled(false);
    ui->actionPause->setEnabled(true);
    ui->actionStop->setEnabled(true);
    ui->actionPause->setIcon(QIcon(":/icons/Step-Forward-Normal-icon.png"));
}

void MainWindow::stopBot()
{
    ui->actionStart->setEnabled(true);
    ui->actionPause->setEnabled(true);
    ui->actionStop->setEnabled(false);
    ui->actionPause->setIcon(QIcon(":/icons/Step-Forward-Normal-Red-icon.png"));
    ui->actionPause->setChecked(false);
}

void MainWindow::createTrayIcon()
{
    if (trayIconMenu == 0)
    {
        trayIconMenu = new QMenu(this);
        if (ui->quitAction != 0)
        {
            trayIconMenu->addAction(ui->quitAction);

            trayIcon = new QSystemTrayIcon(this);
            trayIcon->setContextMenu(trayIconMenu);
            QIcon icon(":/icons/botva.png");
            trayIcon->setIcon(icon);
            connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
                    this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
            trayIcon->show();
        }
    }
}

void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason)
    {
        case QSystemTrayIcon::Trigger:
        case QSystemTrayIcon::DoubleClick:
            if (isVisible())
            {
                hide();
            }
            else
            {
                show();
            }
            break;
        case QSystemTrayIcon::MiddleClick:
            break;
        default:
            ;
    }
}

void MainWindow::timeRefresh()
{
    QString dateTimeString;
    QDateTime dateTime = QDateTime::currentDateTime();
    dateTimeString = tr("%1  %2").arg(dateTime.date().toString("d.MM.yyyy")).arg(dateTime.time().toString("hh:mm:ss"));
    clockLabel->setText(dateTimeString);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (userReallyWantsToQuit())
    {
        writeSettings();
        event->accept();
    }
    else
    {
        event->ignore();
    }
}

void MainWindow::writeSettings()
{
//    QSettings settings("Niimailtah Soft", "BotvaBot");
    QSettings settings("botva.ini", QSettings::IniFormat);

    settings.beginGroup("MainWindow");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
    settings.setValue("mainSplitterSizes", ui->mainSplitter->saveState());
    settings.setValue("logSplitterSizes",  ui->logSplitter->saveState());
    settings.setValue("infoSplitterSizes", ui->infoSplitter->saveState());
    settings.endGroup();
}

void MainWindow::readSettings()
{
//    QSettings settings("Niimailtah Soft", "BotvaBot");
    QSettings settings("botva.ini", QSettings::IniFormat);

    settings.beginGroup("MainWindow");
    ui->mainSplitter->restoreState(settings.value("mainSplitterSizes").toByteArray());
    ui->logSplitter->restoreState(settings.value("logSplitterSizes").toByteArray());
    ui->infoSplitter->restoreState(settings.value("infoSplitterSizes").toByteArray());
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("windowState").toByteArray());
    settings.endGroup();
    settings.beginGroup("Profile");
    nick = settings.value("nick").toString();
    gameServer = settings.value("server").toString();
//    password = settings.value("password").toString();
    autostart = settings.value("autostart", false).toBool();
    settings.endGroup();
}

bool MainWindow::userReallyWantsToQuit()
{
    return true;
}

void MainWindow::aboutBotvaBot()
{
    AboutDialog aboutDialog(this);
    QRect screenSize = qApp->desktop()->screenGeometry();
    aboutDialog.move((screenSize.width() - aboutDialog.width())/2,
                     (screenSize.height() - aboutDialog.height())/2);
    aboutDialog.exec();
}

void MainWindow::options()
{
    optionsDialog->show();
}

//======================================= DEBUG =======================================================

void MainWindow::debug1()
{
    QString line, lastLine;
    int i = 0, j = 0;
    bool firstTime = true;
    struct TransProb
    {
        int factor;
        QVector<double> transProb;
        TransProb()
        {
            factor = 9;
            transProb << 1./9 << 1./9 << 1./9
                      << 1./9 << 1./9 << 1./9
                      << 1./9 << 1./9 << 1./9;
        }
    };
    TransProb probTable[9];

    QString fileName("./data/glade.small");
    QFile *in = new QFile(fileName);
    QTextStream inStream(in);
    in->open(QIODevice::ReadOnly);
    while (true)
    {
        line = inStream.readLine();
        if (line.isNull())
        {
            break;
        }
        if (!firstTime)
        {
            for (i = 0; i < 9; ++i)
            {
                if (lastLine[i] == '1')
                {
                    probTable[i].factor += 3;
                    for (j = 0; j < 9; ++j)
                    {
                        if (line[j] == '1')
                        {
                            probTable[i].transProb[j] =
                                double((probTable[i].factor - 9) / 3 + 1) / probTable[i].factor;
                        }
                        else
                        {
                            probTable[i].transProb[j] =
                                double((probTable[i].factor - 9) / 3) / probTable[i].factor;
                        }
                    }
                }
            }
        }
        lastLine = line;
        firstTime = false;
    }
    in->close();
    delete in;
    in = 0;

    for (i = 0; i < 9; ++i)
    {
        for (j = 0; j < 9; ++j)
        {
            QString val;
            val.setNum(probTable[i].transProb[j]);
//            ui->smallGladeTableWidget->setItem(i, j, new QTableWidgetItem(val));
        }
    }

//    QVector<QLabel *> cells;
//    cells << ui->cellLabel1 << ui->cellLabel2 << ui->cellLabel3
//          << ui->cellLabel4 << ui->cellLabel5 << ui->cellLabel6
//          << ui->cellLabel7 << ui->cellLabel8 << ui->cellLabel9;
//    QLabel *label;
//    i = 0;
//    foreach (label, cells)
//    {
//        if (lastLine[i] == '1')
//        {
//            label->setPixmap(QPixmap(":/icons/mine_plane1.gif"));
//        }
//        ++i;
//    }
}

void MainWindow::debug2()
{
//    ui->pushButton2->setIcon(icons.icon(43));
}










